//
//  Array+AD.swift
//  ADKit
//
//  Created by Adoma on 2020/10/27.
//

import Foundation

extension Collection {
    
    /// by ADKit
    public subscript (safe index: Index) -> Iterator.Element? {
        return indices.contains(index) ? self[index] : nil
    }
}

extension Collection {
    
    /// by ADKit
    public var random: Element? { randomElement() }
}

extension Array {
    
    /// by ADKit
    public func max<T: Comparable>(by keyPath: KeyPath<Element, T>) -> Element? {
        self.max { $0[keyPath: keyPath] < $1[keyPath: keyPath] }
    }
    
    /// by ADKit
    public func maxValue<T: Comparable>(by keyPath: KeyPath<Element, T>) -> T? {
        self.max(by: keyPath)?[keyPath: keyPath]
    }
    
    /// by ADKit
    public func firstIndexElement(where predicate: (Element) -> Bool) -> (Int, Element)? {
        guard let idx = self.firstIndex(where: predicate) else {
            return nil
        }
        return (idx, self[idx])
    }
}

extension Dictionary {
    
    /// by ADKit
    public func max<T: Comparable>(by keyPath: KeyPath<Value, T>) -> (key: Key, value: Value)? {
        self.max { $0.value[keyPath: keyPath] < $1.value[keyPath: keyPath] }
    }
    
    /// by ADKit
    public func maxValue<T: Comparable>(by keyPath: KeyPath<Value, T>) -> T? {
        self.max(by: keyPath)?.value[keyPath: keyPath]
    }
}
